package com.bootx.service.impl;

import com.bootx.common.Page;
import com.bootx.common.Pageable;
import com.bootx.dao.WriteToolDao;
import com.bootx.entity.WriteTool;
import com.bootx.entity.WriteToolCategory;
import com.bootx.repository.WriteToolRepository;
import com.bootx.service.WriteToolService;
import jakarta.annotation.Resource;
import jakarta.persistence.criteria.Predicate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

/**
 * @author black
 */
@Service
public class WriteToolServiceImpl extends BaseServiceImpl<WriteTool,Long> implements WriteToolService {

    @Resource
    private WriteToolDao writeToolDao;
    @Resource
    private WriteToolRepository writeToolRepository;

    @Override
    public WriteTool create(WriteTool writeTool, WriteToolCategory writeToolCategory) {
        WriteTool writeTool1 = writeToolDao.find("path", writeTool.getPath());
        if (writeTool1 != null) {
            writeTool1.setIcon(writeTool.getIcon());
            writeTool1.setMemo(writeTool.getMemo());
            writeTool1.getWriteToolCategories().add(writeToolCategory);
            return super.update(writeTool1);
        }
        writeTool.getWriteToolCategories().add(writeToolCategory);
        return super.save(writeTool);
    }


    @Override
    public Page<WriteTool> findPage(Pageable pageable, String name, WriteToolCategory textAppCategory) {
        org.springframework.data.domain.Page<WriteTool> all = writeToolRepository.findAll((Specification<WriteTool>) (root, query, criteriaBuilder) -> {
            Predicate restrictions = criteriaBuilder.conjunction();
            if (StringUtils.isNotBlank(name)) {
                restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("name"), name));
            }
            return restrictions;
        }, org.springframework.data.domain.Pageable.ofSize(pageable.getPageSize()).withPage(pageable.getPageNumber() - 1));


        return new Page<>(all.getContent(),all.getTotalElements(),pageable);
    }
}
